#include "model3d.h"

namespace tri{

std::map<std::string,tri::TMesh*> TModel3D::mModelList;

TModel3D::TModel3D(): tri::TEntity(){}
TModel3D::~TModel3D(){}


void TModel3D::setModel(std::string model){
	mModel = model;
	mTextures.clear();
}

void TModel3D::setModelTexture(std::string file, std::string model){
	if (model == ""){
		mTextures.clear();
	}
	mTextures[model] = file;
}

bool TModel3D::exists(std::string key){
	return mModelList[key] != NULL;
}

void TModel3D::setOffsetPosition(tri::TVector pos){
	mOffsetPosition = pos;
}

void TModel3D::setOffsetRotation(tri::TVector rot){
	mOffsetRotation = rot;
}

void TModel3D::display(){
	if(!TModel3D::exists(mModel)){
		TModel3D::loadModel(mModel);
	}
	
	
	if(TModel3D::exists(mModel)){
		tri::TMesh* mesh = mModelList[mModel];
		
		std::map<std::string,std::string>::iterator it;
		for ( it=mTextures.begin() ; it != mTextures.end(); it++ ){
			mesh->setModelTexture((*it).second,(*it).first);
		}
		
		glPushMatrix();
		graphics::translate(mOffsetPosition);
		graphics::rotate(mOffsetRotation);
		mesh->render();
		glPopMatrix();
	}
}

void TModel3D::deleteModel(std::string key){
	if (TModel3D::exists(key)){
		tri::TMesh* group = mModelList[key];
		delete group;
		mModelList.erase(key);
	}
}

bool TModel3D::loadModel(std::string key,std::string _file){
	if(_file == ""){
		_file = key;
	}
	
	if(!tri::sys::exists(_file)){
		tri::LOG_SEVERE("Unable to locate model file...:"+_file );
		return false;
	}
	
	tri::LOG_INFO("Loading Model from "+_file+" ..." );
	tri::TMesh* mesh = tri::TMesh::loadObjMesh(_file.c_str());
	if (mesh == NULL){
		tri::LOG_SEVERE("Unable to load model from file...:"+_file );
		return false;
	}
	
	if (TModel3D::exists(key)){
		deleteModel(key);
	}
	
	mModelList[key] = mesh;
	return true;
}


}
